<template>
  <div id="itemBox">
    <!-- 查询子组件 -->
    <SearchForm v-on:search-form="getSearchForm"></SearchForm>
    <!-- <el-row>
      <el-col :span="2">
        <el-button type="primary" @click="oneKeySale">一键生成订单</el-button>
      </el-col>
    </el-row> -->
    <el-row>
      <template>
        <el-table
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="450"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="商品编号" width="100"></el-table-column>
          <el-table-column prop="itemName" label="商品名称" width="200"></el-table-column>
          <el-table-column prop="price" label="定价"></el-table-column>
          <el-table-column prop="className" label="分类"></el-table-column>
          <el-table-column prop="brand" label="品牌"></el-table-column>
          <el-table-column prop="isSaled" label="状态">
            <template slot-scope="scope">
              <!--  | filterisStutas过滤器 -->
              <span
                :class="addClassStatus(scope.row.isSaled)"
              >{{scope.row.isSaled | filterIsSaled}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="上架时间"></el-table-column>
          <el-table-column fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
              <el-button
                @click="handleSaleClick(scope.$index,scope.row)"
                :disabled="scope.row.isSaled===0?true:false"
                type="text"
                size="small"
              >生成订单</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin-top: 10px;"
          background
          layout="sizes,prev, pager, next"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 20, 40]"
          :current-page="pageNumber"
          :page-size="pageSize"
          :total="total"
        >
          <!-- pageNumber 和pageSize触发 -->
        </el-pagination>
      </template>
    </el-row>
    <!-- 查看商品信息对话框 -->
    <el-dialog title="商品信息" :visible.sync="dialogItemInfoFormVisible">
      <el-form :model="itemInfoForm">
        <el-form-item label="商品编号" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.id" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.itemName" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="定价" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.price" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="分类" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.className" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="品牌" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.brand" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.status" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="上架时间" :label-width="formLabelWidth">
          <el-input v-model="itemInfoForm.createTime" autocomplete="off" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogItemInfoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogItemInfoFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 生成订单对话框 -->
    <el-dialog title="订单" :visible.sync="dialogSaleFormVisible">
      <el-form :model="saleForm" label-width="80px" ref="saleForm">
        <el-row>
          <el-table :data="saleForm.saleTableData">
            <el-table-column property="itemName" label="商品名称" width="300"></el-table-column>
            <el-table-column property="price" label="定价" width="200"></el-table-column>
            <el-table-column fixed="right" label="商品数量" prop="number">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.number"
                  :change="handleNumberChange"
                  :min="1"
                  label="商品数量"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="saleForm.description"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="总金额" v-model="saleForm.tocalCount">
            <!-- 总金额计算方法 -->
            <span class="statusFaile">{{total_price}}￥</span>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" plain @click="paySale('saleForm',1)">立即支付</el-button>
        <el-button @click="dialogSaleFormVisible = false,closeSaleDialog('saleForm')">取 消</el-button>
        <el-button type="primary" @click="dialogSaleFormVisible = false,closeSaleDialog('saleForm'),paySale('saleForm',0)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SearchForm from "@/components/common/SearchForm";
import axios from "axios";
import qs from "qs";

const baseUrl = "http://47.102.99.195:8888";
export default {
  props: {
    //父组件向子组件传递数据
  },
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      total: 0,
      pageNumber: 1,
      pageSize: 10,
      searchForm: {
        //查询表单数据
        className: "",
        itemNumbwe: "",
        brand: "",
        itemName: "",
        createTime: ""
      },
      loading: true, //是否使用加载
      dialogItemInfoFormVisible: false, //查看弹窗标记
      itemInfoForm: {
        //弹窗表单
        id: "",
        itemName: "",
        price: "",
        className: "",
        brand: "",
        isSaled: "",
        createTime: "",
        status: ""
      },
      formLabelWidth: "80px", //弹窗长度大小
      dialogSaleFormVisible: false, //生成订单弹窗
      saleForm: {
        //订单表单
        saleTableData: [],
        description: "",
        tocalCount: ""
      }
    };
  },
  mounted() {
    this.getData();
  },
  computed: {
    //计算总金额
    total_price: function() {
      let sum_price = 0;
      this.saleForm.saleTableData.forEach(item => {
        sum_price += item.price * item.number;
      });
      return sum_price;
    }
  },
  methods: {
    /**
     * 获取商品数据
     */
    getData() {
      axios
        .post(baseUrl + "/item/searchItem?", this.searchForm, {
          params: {
            pageNumber: this.pageNumber,
            pageSize: this.pageSize
          }
        })
        .then(res => {
          console.log("获取数据查询form===>>>");
          console.log(this.searchForm);
          if(res.data.obj==null){
            this.$message({
            type:"info",
            message:"无数据"
          })
          }
          this.tableData = res.data.obj;
          // 总页数
          this.total = res.data.maxCount;
        })
        .catch(function(error) {
          console.log(error);
        });
      this.loading = false;
    },
    /**
     * 获取查询表单数据
     */
    getSearchForm: function(searchForm) {
      this.searchForm = searchForm;
      console.log(`父组件查询表单====》`);
      console.log(this.searchForm);
      //触发查询数据方法
      this.getData();
    },
    /**
     * 添加商品状态样式
     */
    addClassStatus(i) {
      switch (i) {
        case 0:
          return "statusFaile";
        case 1:
          return "statusSuccess";
      }
    },
    /**
     * 查看方法
     */
    handleClick(row) {
      this.dialogItemInfoFormVisible = true;
      this.itemInfoForm = row;
      if (this.itemInfoForm.isSaled == 0) {
        this.itemInfoForm.status = "已下架";
      } else if (this.itemInfoForm.isSaled == 1) {
        this.itemInfoForm.status = "售卖中";
      }
      console.log("选中单行==================》");
      console.log(row);
    },
    /**
     * 生成订单
     */
    handleSaleClick(index, row) {
      console.log("生成订单===========>>>");
      console.log(index, row);
      this.dialogSaleFormVisible = true;
      //1.赋值给商品表
      var temp = {
        id: "",
        itemName: "",
        price: "",
        number: 1
      };
      temp.id = row.id;
      temp.itemName = row.itemName;
      temp.price = row.price;
      this.saleForm.saleTableData.push(temp);
      console.log(this.saleForm.saleTableData);
    },
    /**
     * 更改数量
     */
    handleNumberChange() {
      console.log("更改商品数量233333");
      // this.handleSaleClick(index,row);
    },
    /**
     * 一键生成订单
     */
    oneKeySale: function(rows) {},
    /**
     * 立即支付
     */
    paySale(form,flag) {
      console.log(`立即支付=====>>>${flag}`);

      this.dialogSaleFormVisible = false; //关闭弹窗

      var dtos = [];

      //解决js 数组值被覆盖
      var datas = this.saleForm.saleTableData;
      console.log('datas');
      console.log(datas);
      for(var i in  datas){
        //内部自定义对象
        var temp = {};
        temp.itemId = datas[i].id;
        temp.itemName = datas[i].itemName;
        temp.number = datas[i].number;
        console.log(temp);

        dtos.push(temp);
      }
      console.log('dtos');

      console.log(dtos);

      var count = this.total_price;
      var description = this.saleForm.description;

      //保存数据到后台
      axios.post(baseUrl+"/item/oneKeySale",dtos,{
        params:{
          count:count,
          description:description,
          isPayed:flag
        }
      },{
        header:{"Content-Type":"application/json"}
      }).then(res=>{
        if(res.data.event ==0){
          var msg ="";
          if(flag==1){
            msg = "支付成功";
          }else{
            msg = "已加入订单列表";
          }
          this.$message({
            type:"success",
            message:msg
          });
        }else if(res.data.event==-1){
          this.$message({
            type:"error",
            message:"支付失败，已加入订单列表"
          }).catch(
            this.$message({
            type:"error",
            message:"支付失败，已加入订单列表"}
          ));
        }
      });
    },
    /**
     * 清空对话框备注信息
     */
    closeSaleDialog(formName) {
      // this[formName] = {};//初始化表单
      console.log('点击对话框取消');

      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    },
    /**
     * 更改页码
     */
    handleCurrentChange(pageNumber) {
      this.pageNumber = pageNumber;
      this.getData();
    },
    /**
     * 更改页数
     */
    handleSizeChange: function(size) {
      this.pageSize = size;
      console.log(`页数====》${this.pagesize}`); //每页下拉显示数据
      this.getData();
    }
  },
  //注册组件
  components: {
    SearchForm
  },
  //本地过滤器
  filters: {
    /**
     * 显示是否在售卖中
     */
    filterIsSaled: function(value) {
      if (value === 0) {
        return "已下架";
      }
      if (value === 1) {
        return "售卖中";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.statusFaile {
  color: #f56c6c;
}
.statusSuccess {
  color: #67c23a;
}
</style>
